<?php

// +----------------------------------------------------------------------
// | Admin Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-admin
// | github 代码仓库：https://github.com/zoujingli/think-plugs-admin
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\base\controller\api;

use think\admin\Controller;
use think\admin\Exception;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemFile;
use think\admin\service\AdminService;
use think\admin\Storage;
use think\admin\storage\AliossStorage;
use think\admin\storage\AlistStorage;
use think\admin\storage\LocalStorage;
use think\admin\storage\QiniuStorage;
use think\admin\storage\TxcosStorage;
use think\admin\storage\UpyunStorage;
use think\exception\HttpResponseException;
use think\file\UploadedFile;
use think\Response;
use app\base\controller\api\Auth;
use QCloud\COSSTS\Sts;
/**
 * 文件上传接口
 * @class Upload
 * @package app\admin\controller\api
 */
class UploadTxcos extends Auth
{


    /**
     * 获取上传方式
     * @return string
     * @throws \think\admin\Exception
     */
    private function getType(): string
    {
        $type = strtolower(input('uptype', 'txcos'));
        if (in_array($type, array_keys(Storage::types()))) {
            return $type;
        } else {
            return strtolower(sysconf('storage.type|raw'));
        }
    }

    /**
     * 文件上传入口
     * @throws \think\admin\Exception
     */
    public function file()
    {

        // 开始处理文件上传
        $file = $this->getFile();
        $extension = strtolower($file->getOriginalExtension());
        $saveFileName = input('key') ?: Storage::name($file->getPathname(), $extension, '', 'md5_file');
        // 检查文件名称是否合法
        if (strpos($saveFileName, '..') !== false) {
            $this->error('文件路径不能出现跳级操作！');
        }
        // 检查文件后缀是否被恶意修改
        if (strtolower(pathinfo(parse_url($saveFileName, PHP_URL_PATH), PATHINFO_EXTENSION)) !== $extension) {
            $this->error('文件后缀异常，请重新上传文件！');
        }
        // 屏蔽禁止上传指定后缀的文件
        if (!in_array($extension, str2arr(sysconf('storage.allow_exts|raw')))) {
            $this->error('文件类型受限，请在后台配置规则！');
        }

        if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
            $this->error('文件安全保护，禁止上传可执行文件！');
        }

        // 读取配置文件
        $region  = sysconf('storage.txcos_point|raw');
        $bucket = sysconf('storage.txcos_bucket|raw');
        $secretId = sysconf('storage.txcos_access_key|raw');
        $secretKey = sysconf('storage.txcos_secret_key|raw');
        // 计算链接前缀
        $host = strtolower(sysconf('storage.txcos_http_domain|raw'));
        $type = strtolower(sysconf('storage.txcos_http_protocol|raw'));
        if ($type === 'auto') {
            $domain = "//{$host}";
        } elseif (in_array($type, ['http', 'https'])) {
            $domain = "{$type}://{$host}";
        } else {
            throw new Exception(lang('未配置腾讯云域名'));
        }

        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => "ap-shanghai",
                'scheme' => 'http', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey)));
        //$local_path = $domain."/".$saveFileName; //保存到用户本地路径
        // $bina = file_get_contents($file->getPathname());
        $result = $cosClient->upload(
            $bucket, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
            $key = $saveFileName, //此处的 key 为对象键
            $body = fopen($file->getPathname(), 'rb')
        );

//        dump($result);
//        $data = $result->getBody()->getContents();
//       dump($data);
        $this->success('上传成功11111！', ['url'=>$domain."/".$saveFileName,'r'=>$result]);



        try {
            $safeMode = $this->getSafe();
            if (($type = $this->getType()) === 'local') {
                $local = LocalStorage::instance();
                $distName = $local->path($saveFileName, $safeMode);
                if (PHP_SAPI === 'cli') {
                    is_dir(dirname($distName)) || mkdir(dirname($distName), 0777, true);
                    rename($file->getPathname(), $distName);
                } else {
                    $file->move(dirname($distName), basename($distName));
                }
                $info = $local->info($saveFileName, $safeMode, $file->getOriginalName());
                if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
                    if ($this->imgNotSafe($distName) && $local->del($saveFileName)) {
                        $this->error('图片未通过安全检查！');
                    }
                    [$width, $height] = getimagesize($distName);
                    if (($width < 1 || $height < 1) && $local->del($saveFileName)) {
                        $this->error('读取图片的尺寸失败！');
                    }
                }
            } else {

                try {
                    $cosClient = new \Qcloud\Cos\Client(
                        array(
                            'region' => "ap-shanghai",
                            'scheme' => 'http', //协议头部，默认为http
                            'credentials'=> array(
                                'secretId'  => $secretId ,
                                'secretKey' => $secretKey)));
                    //$local_path = $domain."/".$saveFileName; //保存到用户本地路径
                    // $bina = file_get_contents($file->getPathname());
                    $result = $cosClient->upload(
                        $bucket, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
                        $key = $saveFileName, //此处的 key 为对象键
                        $body = fopen($file->getPathname(), 'rb')
                    );
                    // 请求成功
                    $this->success('文件上传成功111！', ['s'=>$saveFileName,"r"=>$result['RequestId']]);
                    print_r($result);
                } catch (\Exception $e) {
                    // 请求失败
                    $this->error('文件失败！', $e);
                    echo($e);
                }






               // $info = Storage::instance($type)->set($saveFileName, $bina, $safeMode, $file->getOriginalName());
            }
            if (isset($info['url'])) {
                $this->success('文件上传成功！', ['url' => $safeMode ? $saveFileName : $info['url']]);
            } else {
                $this->error('文件处理失败，请稍候再试！');
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取上传类型
     * @return boolean
     */
    private function getSafe(): bool
    {
        return boolval(input('safe', '0'));
    }



    /**
     * 获取文件对象
     * @return UploadedFile|void
     */
    private function getFile(): UploadedFile
    {
        try {
            $file = $this->request->file('file');
            if ($file instanceof UploadedFile) {
                return $file;
            } else {
                $this->error('读取临时文件失败！');
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            trace_file($exception);
            $this->error(lang($exception->getMessage()));
        }
    }

    /**
     * 检查图片是否安全
     * @param string $filename
     * @return boolean
     */
    private function imgNotSafe(string $filename): bool
    {
        $source = fopen($filename, 'rb');
        if (($size = filesize($filename)) > 512) {
            $hexs = bin2hex(fread($source, 512));
            fseek($source, $size - 512);
            $hexs .= bin2hex(fread($source, 512));
        } else {
            $hexs = bin2hex(fread($source, $size));
        }
        if (is_resource($source)) fclose($source);
        $bins = hex2bin($hexs);
        /* 匹配十六进制中的 <% ( ) %> 或 <? ( ) ?> 或 <script | /script> */
        foreach (['<?php ', '<% ', '<script '] as $key) if (stripos($bins, $key) !== false) return true;
        $result = preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexs);
        return $result === false || $result > 0;
    }

    /**
     * 文件上传检查
     */
    public function state()
    {
        try {

            [$name, $safe] = [input('name'), $this->getSafe()];
            $data = ['uptype' => $this->getType(), 'safe' => intval($safe), 'key' => input('key')];
            $txcos = TxcosStorage::instance();
            $token = $txcos->token($data['key'], 3600, $name);
            $data['url'] = $token['siteurl'];
            $data['q-ak'] = $token['q-ak'];
            $data['policy'] = $token['policy'];
            $data['q-key-time'] = $token['q-key-time'];
            $data['q-signature'] = $token['q-signature'];
            $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
            $data['server'] = $txcos->upload();
            $this->success('获取上传授权参数', array_merge($data, ['id' => $file->id ?? 0]), 404);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    public function getTempKeys()
    {
        $bucket = sysconf('storage.txcos_bucket|raw');
        $secretId = sysconf('storage.txcos_access_key|raw');
        $secretKey = sysconf('storage.txcos_secret_key|raw');
        // 计算链接前缀
        $host = strtolower(sysconf('storage.txcos_http_domain|raw'));
        $type = strtolower(sysconf('storage.txcos_http_protocol|raw'));
        if ($type === 'auto') {
            $domain = "//{$host}";
        } elseif (in_array($type, ['http', 'https'])) {
            $domain = "{$type}://{$host}";
        } else {
            throw new Exception(lang('未配置腾讯云域名'));
        }
        $sts = new Sts();
        $config = array(
            'url' => "https://sts.tencentcloudapi.com/", // url和domain保持一致
           // 'domain' =>$host, // 域名，非必须，默认为 sts.tencentcloudapi.com
            'proxy' => '',
            'secretId' => $secretId, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'secretKey' => $secretKey, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'bucket' => $bucket, // 换成你的 bucket
            'region' => 'ap-shanghai', // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix' => array('*'), // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => array (
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ),

        );

        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        $this->success('获取上传参数成功', $tempKeys);
    }
}
